package com.magicborrow.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.beans.AddressBean;
import com.magicborrow.beans.UserBean;
import com.magicborrow.utils.BitmapUtils;
import com.magicborrow.utils.HttpRequest;
import com.magicborrow.utils.ImageUploadAsyncTask;
import com.magicborrow.utils.ImageUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.view.SexDialog;
import com.magicborrow.views.LoadingDialog;
import com.magicborrow.views.SelectSexDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/5/17.
 */
public class EditInfoActivity extends BaseActivity implements View.OnClickListener {


    private ImageView mAvatar;
    private TextView tvName;
    private TextView tvPhoneNumber;
    private TextView tvAddressOne;
    private TextView tvAddressTwo;
    private TextView tvGender;

    private Intent intent;
    private TextView tvSignature;
    //    private TextView tvBirthday;
    private TextView tvCity;

    public static final String TYPE_MODIFY = "TYPE_MODIFY";
    private String picPath;
    private SelectSexDialog selectSexDialog;
    private SexDialog sexDialog;
    private UserBean.User user;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_info);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        mAvatar = (ImageView) findViewById(R.id.avatar);//头像
        tvName = (TextView) findViewById(R.id.nickname);//名字
        tvPhoneNumber = (TextView) findViewById(R.id.phonenumber);//电话号码
        tvAddressOne = (TextView) findViewById(R.id.address_one);//服务地址
        tvAddressTwo = (TextView) findViewById(R.id.address_two);
        tvGender = (TextView) findViewById(R.id.tv_gender);
//        tvBirthday = (TextView) findViewById(R.id.tv_birthday);
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvSignature = (TextView) findViewById(R.id.tv_signature);
    }

    private void initData() {
        user = UserTools.getUser(this);
        if (user != null) {
            DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(getResources().getDimensionPixelOffset(R.dimen._20dp))).build();
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(Constants.ADDRESS + user.getAvatar80(),
                    mAvatar, options);
            tvName.setText(user.getNickname());
            tvPhoneNumber.setText(user.getMobile());
            tvGender.setText(user.getGender() == 1 ? "男" : "女");
            tvSignature.setText(getIntent().getStringExtra("signature"));
        }
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
    }

    private void initListener() {
        mAvatar.setOnClickListener(this);
        findViewById(R.id.rl_avatar).setOnClickListener(this);
        findViewById(R.id.rl_name).setOnClickListener(this);
        findViewById(R.id.rl_phonenumber).setOnClickListener(this);
        findViewById(R.id.rl_address).setOnClickListener(this);
        findViewById(R.id.rl_signature).setOnClickListener(this);
        findViewById(R.id.rl_location).setOnClickListener(this);
        findViewById(R.id.confirm).setOnClickListener(this);
        findViewById(R.id.rl_sex).setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_avatar:
            case R.id.avatar:
                intent = new Intent(this, SelectPicActivity.class);
                intent.putExtra("cropPhoto", true);
                startActivityForResult(intent, Constants.REQUEST_ONE);
                break;
            case R.id.rl_name:
                intent = new Intent(this, GoPersonInfoActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra(TYPE_MODIFY, tvName.getText().toString().trim());
                startActivityForResult(intent, Constants.REQUEST_TWO);
                break;
            case R.id.rl_phonenumber:
                intent = new Intent(this, PasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_address:
                intent = new Intent(this, PasswordActivity.class);
                intent.putExtra("type", 2);
                Bundle bundle = new Bundle();
                bundle.putString("address1", tvAddressOne.getText().toString().trim());
                bundle.putString("address2", tvAddressTwo.getText().toString().trim());
                intent.putExtras(bundle);
                startActivityForResult(intent, Constants.REQUEST_TWO);
                break;
            case R.id.rl_signature:
                intent = new Intent(this, GoPersonInfoActivity.class);
                intent.putExtra("type", 3);
                intent.putExtra(TYPE_MODIFY, tvSignature.getText().toString().trim());
                startActivityForResult(intent, Constants.REQUEST_TWO);
                break;
            case R.id.rl_location:
                intent = new Intent(this, AddressManagerActivity.class);
                startActivityForResult(intent, Constants.REQUEST_THREE);
                break;
            case R.id.confirm:
                saveModify();
                break;
            case R.id.rl_sex:
                sexDialog = new SexDialog(this);
                sexDialog.show();
                sexDialog.setTallButtonListener(new SexDialog.TallButtonListener() {
                    @Override
                    public void onPositiveButton(SexDialog dialog) {
                        tvGender.setText(dialog.getSex());
                        dialog.dismiss();
                    }

                    @Override
                    public void onNegativeButton(SexDialog dialog) {
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_ONE) {
            picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
            mAvatar.setImageBitmap(BitmapUtils.toRoundBitmap(ImageUtil.readFile(picPath), 1, R.color.white));
        }
        if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_THREE) {
            AddressBean address = (AddressBean) data.getSerializableExtra("address");
            tvCity.setText(address.getAddressInfo());
        }
        if (requestCode == Constants.REQUEST_TWO) {
            if (null == data) {
                return;
            }
            String content = data.getStringExtra("content");
            switch (resultCode) {
                case 0:
                    tvName.setText(content);
                    break;
                case 1:
                    tvPhoneNumber.setText(content);
                    break;
                case 2:
                    String[] split = content.split("#");
                    tvAddressOne.setText(split[0]);
                    tvAddressTwo.setText(split[1]);
                    break;
                case 3:
                    tvSignature.setText(content);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void saveModify() {
        loadingDialog.show();
        HashMap<String, String> params = new HashMap<>();
        String name = tvName.getText().toString().trim();
        String signature = tvSignature.getText().toString().trim();
        String gender = tvGender.getText().toString().trim();

        float lat = UserTools.getUser(this).getLat();
        float lon = UserTools.getUser(this).getLon();
        params.put("nickname", name + "");
        params.put("gender", (gender.equals("男") ? 1 : 2) + "");
        params.put("signature", signature + "");
        params.put("lat", lat + "");
        params.put("lon", lon + "");
        params.put("acc_token", user.getAcc_token());

        System.out.println("acc_token-----》" + user.getAcc_token());

        HashMap<String, File> files = new HashMap<>();
        if (picPath != null) {
            files.put("file", new File(picPath));
        }
        new ImageUploadAsyncTask(params, files, "file", Constants.URL_POST_PERSON_INFO, new HttpRequest.HttpRequestListener() {
            @Override
            public void httpError() {
                loadingDialog.dismiss();
            }

            @Override
            public void httpSuccess(String msg) {
                Gson gson = new Gson();
                UserBean entity = gson.fromJson(msg, UserBean.class);
                if (entity.getCode() == 0) {
                    UserBean.User data = entity.getData();
                    data.setPassword(UserTools.getUser(EditInfoActivity.this).getPassword());
                    data.setAcc_token(user.getAcc_token());
                    UserTools.saveUser(EditInfoActivity.this, data);
                    finish();
                    Toast.makeText(EditInfoActivity.this, entity.getMessage(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(EditInfoActivity.this, entity.getMessage(), Toast.LENGTH_SHORT).show();
                }
                loadingDialog.dismiss();
            }
        }).execute();
    }
}
